package com.fast.gateway.advice;


import com.fast.common.em.ResultEm;
import com.fast.common.pojo.resp.Result;
import com.fast.gateway.exception.NotAuthException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


@Slf4j
@Order(-1)
@Configuration
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class GlobalExceptionHandler implements ErrorWebExceptionHandler {

    private final ObjectMapper objectMapper;

    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        log.error("网关全局异常拦截======>> 算了吧", ex);
        ServerHttpResponse response = exchange.getResponse();
        if (response.isCommitted()) {
            return Mono.error(ex);
        }
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        return response.writeWith(Mono.fromSupplier(() -> {
            DataBufferFactory bufferFactory = response.bufferFactory();
            try {
                Result<Void> judge = judge(ex);
                DataBuffer wrap = bufferFactory.wrap(objectMapper.writeValueAsBytes(judge));
                return wrap;
            } catch (JsonProcessingException e) {
                log.error("网关全局异常拦截转换信息", ex);
            }
            return null;
        }));
    }

    /**
     * 判断异常类型
     */
    private Result<Void> judge(Throwable ex) {
        if (ex instanceof NotAuthException) {
            return Result.error(ResultEm.UN_AUTHORIZED, ex.getMessage());
        }
        if(ex instanceof ResponseStatusException){
            return Result.error(ResultEm.Not_RESOURCE);
        }
        return Result.error(ResultEm.ERROR);
    }
}
